/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.rocketmq.store;

import java.util.concurrent.atomic.AtomicLong;

/**
 * ReferenceResource 是一个抽象类，它提供了资源管理和引用计数的基本框架。
 * 通过这个类，可以实现对资源的生命周期管理，包括引用计数、可用性检查以及清理操作等。以下是对其成员变量的详细解释：
 */
public abstract class ReferenceResource {
    /**
     * 描述：使用 AtomicLong 来保证在多线程环境下对引用计数的操作是原子性的。初始值设为 1，表示资源至少被引用一次。
     * 目的：用于跟踪资源的引用次数，确保资源仅当引用计数降为 0 时才真正释放。
     */
    protected final AtomicLong refCount = new AtomicLong(1);
    /**
     * 类型：volatile boolean
     * 描述：标记资源是否可用。默认值为 true，表示资源当前是可用状态。
     * 目的：提供一种简单的方式来检查资源的状态，避免在资源不可用时继续使用它。
     */
    protected volatile boolean available = true;
    /**
     * 描述：标记资源是否已经完成清理工作。默认值为 false，表示清理尚未开始或正在进行中。
     * 目的：帮助确定资源是否已经完成了所有必要的清理步骤，防止重复清理或过早释放资源。
     */
    protected volatile boolean cleanupOver = false;
    /**
     * 描述：记录第一次调用关闭或清理操作的时间戳。初始值为 0，表示尚未进行任何关闭或清理操作。
     * 目的：可用于计算从首次尝试关闭到实际完成关闭所花费的时间，或者用于限制清理操作的频率等。
     */
    private volatile long firstShutdownTimestamp = 0;

    public synchronized boolean hold() {
        if (this.isAvailable()) {
            if (this.refCount.getAndIncrement() > 0) {
                return true;
            } else {
                this.refCount.getAndDecrement();
            }
        }

        return false;
    }

    public boolean isAvailable() {
        return this.available;
    }

    public void shutdown(final long intervalForcibly) {
        if (this.available) {
            this.available = false;
            this.firstShutdownTimestamp = System.currentTimeMillis();
            this.release();
        } else if (this.getRefCount() > 0) {
            if ((System.currentTimeMillis() - this.firstShutdownTimestamp) >= intervalForcibly) {
                this.refCount.set(-1000 - this.getRefCount());
                this.release();
            }
        }
    }

    public void release() {
        long value = this.refCount.decrementAndGet();
        if (value > 0)
            return;

        synchronized (this) {

            this.cleanupOver = this.cleanup(value);
        }
    }

    public long getRefCount() {
        return this.refCount.get();
    }

    public abstract boolean cleanup(final long currentRef);

    public boolean isCleanupOver() {
        return this.refCount.get() <= 0 && this.cleanupOver;
    }
}
